"""
统一响应格式工具文件
提供标准化的API响应格式，包括成功和错误响应
使用枚举定义响应码，确保响应格式的一致性
原理：通过统一的响应格式，提高API的可维护性和客户端的易用性
"""

from enum import Enum
from typing import Any, Optional, Dict
from pydantic import BaseModel


class ResponseCode(Enum):
    """响应状态码枚举"""
    SUCCESS = (200, "操作成功")
    CREATED = (201, "创建成功")
    BAD_REQUEST = (400, "请求参数错误")
    UNAUTHORIZED = (401, "未授权")
    FORBIDDEN = (403, "权限不足")
    NOT_FOUND = (404, "资源不存在")
    INTERNAL_ERROR = (500, "服务器内部错误")
    
    def __init__(self, code: int, message: str):
        self.code = code
        self.message = message


class ApiResponse(BaseModel):
    """API响应模型"""
    code: int
    message: str
    data: Optional[Any] = None
    timestamp: Optional[str] = None


def success_response(
    data: Any = None,
    message: str = "操作成功",
    code: int = 200
) -> Dict[str, Any]:
    """成功响应"""
    from datetime import datetime
    
    return {
        "code": code,
        "message": message,
        "data": data,
        "timestamp": datetime.now().isoformat()
    }


def error_response(
    message: str = "操作失败",
    code: int = 400,
    data: Any = None
) -> Dict[str, Any]:
    """错误响应"""
    from datetime import datetime
    
    return {
        "code": code,
        "message": message,
        "data": data,
        "timestamp": datetime.now().isoformat()
    }


def paginated_response(
    items: list,
    total: int,
    page: int,
    page_size: int,
    message: str = "获取成功"
) -> Dict[str, Any]:
    """分页响应"""
    return success_response(
        data={
            "items": items,
            "pagination": {
                "total": total,
                "page": page,
                "page_size": page_size,
                "total_pages": (total + page_size - 1) // page_size
            }
        },
        message=message
    )